/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.survey.data;

import static com.vng.zing.survey.data.Base.serialize;
import com.vng.zing.survey.thrift.model.AnswerItem;
import com.vng.zing.survey.thrift.model.AnswerKey;
import com.vng.zing.survey.thrift.model.Error;
import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import kyotocabinet.DB;

/**
 *
 * @author kienpd
 */
public class AnswersData extends Base{
       private static final Lock createLock_ = new ReentrantLock();
    private static AnswersData _instance = null;
    private static int buffer_size_profilevip = 0;
    private DB db;

    public AnswersData() {
        db = new DB();
        if (!db.open("database/answer.kch", DB.OWRITER | DB.OCREATE)) {
            System.err.println("open error: " + db.error());
        }

    }

    public static AnswersData getInstance() {
        if (_instance == null) {
            createLock_.lock();
            try {
                if (_instance == null) {
                    _instance = new AnswersData();
                }
            } finally {
                createLock_.unlock();
            }
        }
        return _instance;
    }
    public Error setAnswer(int idUser,int idSurvey,int idQues, AnswerItem answer){
         AnswerKey answerKey = new AnswerKey(idSurvey, idUser, (short) idQues);
           try {
               byte[] key = serialize(answerKey);
               byte[] value = serialize(answer);
               if(!db.set(key, value)){
                   return Error.ERR_SYSTEM;     
               }
               return Error.SUCCESS;
           } catch (Exception ex) {
               Logger.getLogger(AnswersData.class.getName()).log(Level.SEVERE, null, ex);
           }
    
        return Error.ERR_SYSTEM;
    }
    public AnswerItem getAnswer(int idUser,int idSurvey,int idQues){
                 AnswerKey answerKey = new AnswerKey(idSurvey, idUser, (short) idQues);
                 try {
               byte[] key = serialize(answerKey);
               byte[] value = db.get(key);
               if(value== null){
                 return null; 
               }
               AnswerItem answerItem = new AnswerItem();
               answerItem = (AnswerItem) deserialize(value);
               return answerItem;
               
           } catch (Exception ex) {
               Logger.getLogger(AnswersData.class.getName()).log(Level.SEVERE, null, ex);
           }

    
      return null;
    }
}
